package com.paradox.aggregation.provider.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ChatServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup boss=new NioEventLoopGroup(1);
        EventLoopGroup workers=new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());

        try {
            ServerBootstrap bootstrap=new ServerBootstrap();
            bootstrap.group(boss,workers).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,1024)
                     .childHandler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         protected void initChannel(SocketChannel ch) throws Exception {
                             ChannelPipeline pipeline=ch.pipeline();
                             pipeline.addLast(new StringEncoder());
                             pipeline.addLast(new StringDecoder());
                             pipeline.addLast(new ServerHandler());
                         }
                     });
            ChannelFuture channelFuture=bootstrap.bind(9000).sync();
            System.out.println("服务器已启动！");
            channelFuture.channel().closeFuture().sync();
        }finally {
            boss.shutdownGracefully();
            workers.shutdownGracefully();
        }
    }
}
